package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignClient;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.CartVo;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        // 获取当前请求所对应的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String result = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(result)) {
            // 如果要添加的商品在购物车中没有缓存，则购物车新增商品信息
            CartItem cartItem = new CartItem();
            cartItem.setSkuId(skuId);
            cartItem.setCount(num);
            // 查询当前添加商品的详细信息，并赋值到购物车项目中
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                try {
                    R r = productFeignClient.getSkuInfo(skuId);
                    if (!ObjectUtils.isEmpty(r) && r.getCode() == 0) {
                        SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        cartItem.setTitle(skuInfo.getSkuTitle());
                        cartItem.setImage(skuInfo.getSkuDefaultImg());
                        cartItem.setPrice(skuInfo.getPrice());
                    }
                } catch (Exception e) {

                }
            }, threadPoolExecutor);
            // 查询当前sku的组合信息，并赋值到购物车项目中
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                try {
                    R r = productFeignClient.getSkuSaleAttrValues(skuId);
                    if (!ObjectUtils.isEmpty(r) && r.getCode() == 0) {
                        List<String> stringList = r.getData("stringList", new TypeReference<List<String>>() {
                        });
                        cartItem.setSkuAttr(stringList);
                    }
                } catch (Exception e) {

                }
            }, threadPoolExecutor);
            // 查询赋值完成后，将购物车缓存放入redis中
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();
            String cartCache = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartCache);
            return cartItem;
        } else {
            // 如果要添加的商品在购物车中以有缓存，则直接在购物车中添加数量
            CartItem cartItem = JSON.parseObject(result, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem item = JSON.parseObject(str, CartItem.class);
        return item;
    }

    @Override
    public CartVo getCartVo() throws ExecutionException, InterruptedException {
        CartVo cart = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        // 判断用户是否已登录
        if (userInfoTo.getUserId() != null) {
            // 已登录，首先需要判断临时购物车中是否有购物项需要合并
            List<CartItem> tempCartItems = getListItem(CartConstant.USER_CART_PREFIX + userInfoTo.getUserKey());
            if (!CollectionUtils.isEmpty(tempCartItems)) {
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
            }
            // 合并完成后，获取登录用户的购物车信息
            List<CartItem> userCartItems = getListItem(CartConstant.USER_CART_PREFIX + userInfoTo.getUserId());
            cart.setItems(userCartItems);
            // 清空临时购物车的所有数据
            clearCart(CartConstant.USER_CART_PREFIX + userInfoTo.getUserKey());
        } else {
            // 没登录
            List<CartItem> cartItems = getListItem(CartConstant.USER_CART_PREFIX + userInfoTo.getUserKey());
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        String cartStr = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), cartStr);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String cartStr = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), cartStr);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getOrderItems(Long userId) {
        List<CartItem> userCartItems = getListItem(CartConstant.USER_CART_PREFIX + userId);
        List<CartItem> cartItems = userCartItems.stream().filter(item -> item.getCheck()).collect(Collectors.toList());
        return cartItems;
    }

    /**
     * 获取当前请求所对应的购物车缓存
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CartConstant.USER_CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CartConstant.USER_CART_PREFIX + userInfoTo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }

    /**
     * 获取购物车中的所有购物项
     *
     * @return
     */
    private List<CartItem> getListItem(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (!CollectionUtils.isEmpty(values)) {
            List<CartItem> itemList = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return itemList;
        }
        return null;
    }
}
